//
//  ViewController.swift
//  vhSixMinProject
//
//  Created by moon_zm on 03/18/2025.
//  Copyright (c) 2025 moon_zm. All rights reserved.
//

import UIKit
import vhSixMinProject
import ZMSaaSUIKit
import CoreBluetooth

class ViewController: UIViewController {

    var dataArray:[CBPeripheral] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        addDeviceHandler()
    }

    func addDeviceHandler() {
        ZMBleManager.shared.deviceListHandler = {[weak self] devices in
            guard let self = self else{return}
            self.dataArray = devices
            self.tableV.reloadData()
        }
        ZMBleManager.shared.deviceConnectHandler = {[weak self] isConnect, devName in
            guard let self = self else{return}
            if isConnect {
                devLab.text = "\(devName):"
                descLab.text = ""
            }
        }
        ZMBleManager.shared.deviceRSSI = {[weak self] value in
            guard let self = self else{return}
            descLab.text! += "\(value)\n"
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        scanBtn.frame = CGRectMake(self.view.ex_width - 30 - 80, self.view.ex_top + 80, 80, 40)
        tableV.frame = CGRectMake(self.view.ex_width - 30 - 180, scanBtn.ex_bottom + 20, 180, self.view.ex_height - scanBtn.ex_bottom - 40)
        cancelBtn.frame = CGRectMake(tableV.ex_left, scanBtn.ex_top, scanBtn.ex_width, scanBtn.ex_height)
        devLab.frame = CGRectMake(30, scanBtn.ex_top, self.tableV.ex_left - 30, 40)
        descLab.frame = CGRectMake(30, tableV.ex_top, self.tableV.ex_left - 30, tableV.ex_height)
    }
    
    @objc func scanClick() {
        if ZMBleManager.shared.connectType != .connected {
            ZMBleManager.shared.scanDevice()
        }
    }
    @objc func cancelClick() {
        if ZMBleManager.shared.connectType == .connected {
            ZMBleManager.shared.disconnected()
        }
    }
    
    
    lazy var scanBtn:UIButton = {
        let btn = UIButton(type: .custom)
        btn.ex_setTitle("Scan", font: UIFont.ex_regular(ofSize: 16))
        btn.backgroundColor = .gray
        view.addSubview(btn)
        btn.addTarget(self, action: #selector(scanClick), for: .touchUpInside)
        return btn
    }()
    
    lazy var cancelBtn:UIButton = {
        let btn = UIButton(type: .custom)
        btn.ex_setTitle("Cancel", font: UIFont.ex_regular(ofSize: 16))
        btn.backgroundColor = .gray
        view.addSubview(btn)
        btn.addTarget(self, action: #selector(cancelClick), for: .touchUpInside)
        return btn
    }()
    lazy var devLab:UILabel = {
        let lab = UILabel()
        lab.backgroundColor = .clear
        lab.ex_set(font: UIFont.ex_regular(ofSize: 16), color: .black)
        view.addSubview(lab)
        return lab
    }()
    
    lazy var descLab:UITextView = {
        let lab = UITextView()
        lab.backgroundColor = .clear
        lab.textColor = .black
        lab.text = ""
        lab.font = UIFont.ex_regular(ofSize: 16)
        view.addSubview(lab)
        return lab
    }()
    
    lazy var tableV:UITableView = {
        let v = UITableView(frame: .zero, style: .plain)
        v.separatorStyle = .none
        v.backgroundColor = .clear
        v.showsVerticalScrollIndicator = false
        v.dataSource = self
        v.delegate = self
        view.addSubview(v)
        return v
    }()
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension ViewController :UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "UITableViewCell_Scan"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        cell?.textLabel?.text = self.dataArray[indexPath.row].name
        cell?.detailTextLabel?.text = "\(String(describing: self.dataArray[indexPath.row].rssi))"
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard let name = self.dataArray[indexPath.row].name else {return}
        ZMBleManager.shared.connectDevice(deviceName: name)
    }
}

